import csv
import sys
from ddt import ddt, data, unpack ,file_data
from selenium import webdriver
import time
import unittest

# 对测试文件进行读取
def resulterText(file_name):
    rows = []
    path = sys.path[0]
    # Test_login.txt  所在的路径：脚本路径中的data文件夹里
    with open(path+'/data/'+file_name,'r',encoding='UTF-8') as f:
        readers = csv.reader(f,delimiter=',',quotechar='|')
        next(readers,None)
        for row in readers:
            temprows=[]
            for i in row:
                temprows.append(i)
            rows.append(temprows)
        return rows

@ddt
class register(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.url = "http://127.0.0.1:8080/login.html"
        url = self.url
        driver = self.driver
        driver.get(url)
        driver.find_element_by_id("register").click()
        time.sleep(2)
        self.driver.maximize_window()
        time.sleep(2)


    @data(*resulterText('Test_result.txt'))
    @unpack
    def test_result(self,username,password,repassword):
        driver = self.driver
        driver.get("http://127.0.0.1:8080/register.html")
        driver.find_element_by_id("username").clear()
        driver.find_element_by_id("password").clear()
        driver.find_element_by_id("repassword").clear()
        driver.find_element_by_id("username").send_keys(username)
        driver.find_element_by_id("password").send_keys(password)
        driver.find_element_by_id("repassword").send_keys(repassword)
        time.sleep(2)
        driver.find_element_by_id("register").click()
        time.sleep(2)

        try:
            # 定位弹框(获取弹框的操作句柄)
            alert = driver.switch_to.alert
            driver.implicitly_wait(10)
            # 操作获取的句柄关闭 alter
            alert.accept()
            self.assertEqual("音乐播放器登录页面", driver.title, msg="注册失败")
        except:
            self.assertEqual("音乐播放器登录页面",driver.title,msg="注册失败")

    def tearDown(self):
        self.driver.quit()
        time.sleep(2)

if __name__ == '__main__':
    unittest.main()

